package redis

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
	"math/rand"
	"time"
)

var ErrNil = redis.ErrNil

type TRedLock struct {
	key   string
	value string
}

func (t *TRedLock) Lock(conn redis.Conn, key string, timeout int64) (bSuccess bool, err error) {
	t.key = fmt.Sprintf("__lock_%v__", key)
	t.value = fmt.Sprintf("__red_lock_%v__", rand.Intn(100000))

	for { // 针对问题1，使用循环
		var ret string
		ret, err = String(conn.Do("SET", t.key, t.value, "Nx", "EX", timeout))
		if err != nil && err != ErrNil {
			continue
		}

		if err == ErrNil {
			err = nil
		}

		isLock := ret == "OK"
		if isLock {
			bSuccess = true
			break
		} else {
			time.Sleep(10 * time.Millisecond)
		}
	}
	return
}

func (t *TRedLock) UnLock(conn redis.Conn) (err error) {
	defer conn.Close()
	_, err = conn.Do("Del", t.key)
	return
}

func String(reply interface{}, err error) (string, error) {
	return redis.String(reply, err)
}
